import Vue from "vue";
import Router from "vue-router";
import Home from "@/views/Home.vue";
import store from "../store";
Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "/",
      name: "Home",
      meta: {
        requireAuth: true
      },
      component: Home
      // component: () => import("@/views/Home.vue")
    },
    {
      path: "/About",
      name: "About",
      meta: {
        requireAuth: true
      },
      component: () => import("@/views/About.vue")
    },
    {
      path: "/Login",
      name: "Login",
      component: () => import("@/views/Login.vue")
    },
    {
      path: "/jsArrayA",
      name: "jsArrayA",
      component: () => import("@/views/jsArrayA.vue")
    },
    {
      path: "/jsArrayJJ",
      name: "jsArrayJJ",
      component: () => import("@/views/jsArrayJJ.vue")
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (store.state.loginInfo.token) {
      // 通过vuex state获取当前的token是否存在
      next();
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      });
    }
  } else {
    next();
  }
});

export default router;
